<template>
  <div class="device">
    <el-container class="body">
      <el-header class="bg">
        <div class="header">
          <div class="user">
            <!-- 用户名 -->
            <el-avatar :src=avatar></el-avatar>{{ user }}
          </div>
          <div class="progress">
            <div class="pro-main pro-row">
              <!-- 总进度条 -->
              <el-progress :text-inside="true" :stroke-width="26" :percentage="percent" :format="format"
                :color="customColors"></el-progress>
            </div>
            <el-divider direction="vertical"></el-divider>
            <div class="pro-box pro-row">
              <!-- 个人当日完成量 -->
              <el-tag type="success">当日已完成</el-tag>
              &nbsp;&nbsp;&nbsp;
              <span>{{ userCount.toDayNum }}</span>
            </div>
            <el-divider direction="vertical"></el-divider>
            <div class="pro-box pro-row">
              <!-- 个人总完成量 -->
              <el-tag>完成总量</el-tag>
              &nbsp;&nbsp;&nbsp;
              <span>{{ userCount.totalNum }}</span>
            </div>
            <el-divider direction="vertical"></el-divider>
            <div class="pro-box pro-row">
              <!-- 在线人数 -->
              <el-tag type="info">在线人数</el-tag>
              &nbsp;&nbsp;&nbsp;
              <div slot="content"> {{ userCount.onLine }} </div>
              &nbsp;&nbsp;&nbsp;
              <el-tooltip placement="bottom">
                <div slot="content">{{ userCount.users }}</div>
                <i class="el-icon-info"></i>
              </el-tooltip>
            </div>
          </div>
          <div class="count">
            <el-button type="success" @click="showCount" icon="el-icon-s-data">查看统计数据</el-button>
          </div>
        </div>
      </el-header>
      <el-divider></el-divider>
      <el-main class="data ele-scrollbar">
        <div class="main">
          <el-container v-for="(item, index) in tableData" :key="index" class="card">
            <el-card class="box-card">
              <el-table :data="item" size="small" v-loading="loading[index]">
                <el-table-column label="监控测点名称" prop="newName">
                </el-table-column>
                <el-table-column label="设备类型">
                  <template slot-scope="scope">
                    <el-autocomplete class="inline-input" v-model="scope.row.newNameKey"
                      :fetch-suggestions="querySearch" placeholder="请输入内容" :trigger-on-focus="false" clearable
                      @select="handleSelect"></el-autocomplete>
                  </template>
                </el-table-column>
                <el-table-column label="设备部件">
                  <template slot-scope="scope">
                    <el-input placeholder="请输入内容" v-model="scope.row.sbbj" clearable disabled>
                    </el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-container>
        </div>
        <div class="submit">
          <el-button type="success" round @click="match()" :disabled="isSubmit" icon="el-icon-refresh">刷新匹配</el-button>
          <el-button type="primary" round @click="submit()" :disabled="isSubmit" icon="el-icon-thumb">提交数据</el-button>
          <el-button type="danger" plain @click="exit()" :disabled="isSubmit" icon="el-icon-circle-close">退出系统
          </el-button>
        </div>
        <el-drawer title="梳理统计" :visible.sync="drawer" :direction="direction" size="40%">
          <div id="trend" class="trend" v-loading="loadingCharts"></div>
          <div id="rank" class="rank" v-loading="loadingCharts"></div>
          <div id="pie" class="pie" v-loading="loadingCharts"></div>
        </el-drawer>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import * as echarts from "echarts";
import "@/assets/css/scrollbar.css";
import { length } from "css-tree/lib/lexer/generic";
import { match } from "minimatch";
const axios = require("axios");
export default {
  name: "device",
  data() {
    return {
      user: localStorage.getItem("user"),
      //随机头像
      avatar: "https://api.multiavatar.com/" + localStorage.getItem("user") + ".png",
      // 数据
      tableData: [[], [], []],
      // 加载蒙版
      loading: [false, false, false],
      //统计加载模板
      loadingCharts: false,
      //统计数据
      userCount: {
        toDayNum: 0,
        totalNum: 0,
        online: 0
      },
      initCount: 0,
      remainCount: 0,
      percent: 0,
      //颜色定义
      customColors: [
        { color: "#f56c6c", percentage: 20 },
        { color: "#e6a23c", percentage: 40 },
        { color: "#5cb87a", percentage: 60 },
        { color: "#1989fa", percentage: 80 },
        { color: "#6f7ad3", percentage: 100 },
      ],
      //提交按钮置灰
      isSubmit: false,
      //排行抽屉
      drawer: false,
      //打开方向
      direction: "rtl",
      //趋势统计
      trendOption: {
        title: {
          text: '任务趋势曲线',
          left: 'center'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          top: 30,
          data: ['计划趋势曲线', '剩余趋势曲线']
        },
        series: [
          {
            name: '计划趋势曲线',
            data: [],
            type: 'line',
            areaStyle: {
              opacity: 0.2,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(0, 221, 255)'
                },
                {
                  offset: 1,
                  color: 'rgb(77, 119, 255)'
                }
              ])
            }
          },
          {
            name: '剩余趋势曲线',
            z: 1,
            data: [],
            type: 'line',
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(128, 255, 165)'
                },
                {
                  offset: 1,
                  color: 'rgb(1, 191, 236)'
                }
              ])
            }
          }
        ]
      },
      //统计数据
      option: {
        title: {
          text: '每日统计',
          left: 'center'
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // Use axis to trigger tooltip
            type: "shadow", // 'shadow' as default; can also be 'line' or 'shadow'
          },
        },
        legend: {
          top: 30,
        },
        grid: {
          top: "30%",
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
        },
        yAxis: {
          type: "category",
          data: [],
        },
        series: [],
      },
      //合计统计数据
      countOption: {
        title: {
          text: '总量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: []
        },
        series: [
          {
            name: '姓名',
            type: 'pie',
            radius: '55%',
            center: ['40%', '50%'],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    };
  },
  mounted() {
    //关闭页面的丝带
    if (document.getElementsByTagName("canvas")) {
      let arr = document.getElementsByTagName("canvas");
      for (let i = 0; i < arr.length; i++) {
        arr[i].style.display = "none";
      }
    }
    //初始化数据
    this.getNext();
  },
  methods: {
    //获取下一个数据
    async getNext() {
      let _this = this;
      _this.isSubmit = true;
      //清空数据
      _this.tableData = [];
      _this.loading = [];
      const v = new Date().getTime();
      for (let i = 0; i < 3; i++) {
        _this.loading.push(true);
        await axios
          .get("/ylj/api/getNext?u=" + _this.user + "&v=" + v + "&p=" + i)
          .then(function (response) {
            let r = response.data.data;
            _this.tableData.push(r);
            _this.loading.pop();
          });
      }
      _this.isSubmit = false;
      //获取统计数据
      axios
        .get("/ylj/api/getPersonStatisticalData?user=" + _this.user)
        .then(function (response) {
          let r = response.data.data;
          _this.userCount = r.userCount;
          _this.initCount = r.initCount;
          _this.remainCount = r.remainCount;
          _this.percent = r.percent;

        });
    },
    //格式化百分比统计数据
    format() {
      return this.remainCount + "/" + this.initCount + ' , ' + this.percent + '%';
    },
    //提交数据
    async submit() {
      let _this = this;
      if (_this.tableData[0].length == 0) {
        this.$notify({
          message: "无数据需要提交!",
          type: "error",
        });
        return;
      }
      _this.isSubmit = true;
      //提交是否正常
      let flag = true;
      for (let i = 0; i < 3; i++) {
        await axios
          .post("/ylj/api/submit?user=" + _this.user + "&update=false", _this.tableData[i])
          .then(function (response) {
            let code = response.data.code;
            if (code != 200) {
              flag = false;
            }
          });
      }
      if (flag) {
        this.$notify({
          message: "提交成功!",
          type: "success",
        });
      }
      _this.getNext();
    },
    //刷新匹配
    async match() {
      let _this = this;
      _this.isSubmit = true;
      await axios
        .post("/ylj/api/match?user=" + _this.user, _this.tableData)
        .then(function (response) {
          let data = response.data.data;
          _this.tableData = data;
          _this.$notify({
            message: "刷新成功!",
            type: "success",
          });
        });
      _this.isSubmit = false;
    },
    //查看统计数据
    showCount() {
      let _this = this;
      _this.drawer = true;
      _this.loadingCharts = true;
      //查询排行数据
      axios.get("/ylj/api/getStatisticalData").then(function (response) {
        let r = response.data.data;
        //人员数据
        _this.countOption.legend.data = r.users;
        //全量数据
        _this.countOption.series[0].data = r.allData;
        //设置值
        _this.option.yAxis.data = r.yAxis;
        //先清空
        _this.option.series = [];
        r.datas.forEach((e, i) => {
          let d = {
            name: r.users[i],
            type: "bar",
            stack: "total",
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: e,
          };
          _this.option.series.push(d);
        });
        //趋势统计数据
        axios.get("/ylj/api/getTrendData").then(function (response) {
          let r = response.data.data.data;
          _this.trendOption.xAxis.data = r.dates;
          _this.trendOption.series[0].data = r.should;
          _this.trendOption.series[1].data = r.remain;
          //趋势统计数据
          let trendChart = echarts.init(document.getElementById("trend"));
          trendChart.setOption(_this.trendOption);
        });
        //柱状图
        let chart = echarts.init(document.getElementById("rank"));
        chart.setOption(_this.option);
        //饼图
        let pieChart = echarts.init(document.getElementById("pie"));
        pieChart.setOption(_this.countOption);
        document.querySelector(".el-drawer__body").classList.add('ele-scrollbar');
        _this.loadingCharts = false;
      });
    },
    //退出系统
    async exit() {
      let _this = this;
      await this.$confirm("即将退出系统, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //数据回退
          _this.rollback();
          //退回到登录页
          _this.$router.push("/");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出",
          });
        });
    },
    //数据回退到队列
    async rollback() {
      //回退当前数据
      let _this = this;
      let flag = true;
      for (let i = 0; i < 3; i++) {
        await axios
          .post("/ylj/api/rollback?user=" + _this.user, _this.tableData[i])
          .then(function (response) {
            let code = response.data.code;
            if (code != 200) {
              flag = false;
            }
          });
      }
      return flag;
    },
    //搜索建议
    querySearch(queryString, cb) {
      if (queryString) {
        axios
          .get("/ylj/api/search/" + queryString)
          .then(function (response) {
            let code = response.data.code;
            if (code == 200) {
              let r = response.data.data;
              //回调填充结果
              cb(r);
            }
          });
      }
    },
    //选择
    handleSelect(item) {
    },
  },
};
</script>

<style>
.device {
  height: 900px;
  overflow-y: auto;
}

.body {
  height: 100%;
}

.bg {
  background-color: aliceblue !important;
  height: 20px !important;
}

.header {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.user {
  font-family: "Courier New", Courier, monospace;
  font-size: 20px;
  width: 20%;
}

.progress {
  width: 60%;
  display: flex;
  align-items: center;
  flex-direction: row;
}

.el-progress {
  display: flex;
  align-items: center;
}

.pro-main {
  width: 60%;
}

.pro-box {
  width: 15%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.count {
  width: 20%;
  display: flex;
  align-items: center;
  justify-content: end;
}

.data {
  height: 100%;
}

.main {
  display: flex;
  flex-direction: row;
}

.card {
  height: 100%;
  width: 30%;
  margin: 0 5px 0 5px;
}

.box-card {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

.submit {
  margin-top: 10px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.trend {
  height: 700px;
  width: 100%;
}

.rank {
  height: 700px;
  width: 100%;
}

.pie {
  height: 700px;
  width: 100%;
}
</style>